import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from 'views/home'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

function isLogin() {
  return  !!JSON.parse(sessionStorage.getItem('userInfo'))
}

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    name: 'home',
    component: Home,
  },
  {
    path: '/detail',
    name: 'detail',
    component: () => import('views/home/detail')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('views/login/index.vue')
  },
  {
    path: '/personal-center',
    name: 'personal-center',
    component: () => import('views/personalCenter/index.vue')
  },
  {
    path: '/order-detail',
    name: 'order-detail',
    meta: {
      needLogin: true
    },
    component: () => import('views/personalCenter/orderDetail.vue')
  },
  {
    path: '/shopping-trolley',
    name: 'shopping-trolley',
    meta: {
      needLogin: true
    },
    component: () => import('views/shoppingTrolley/index.vue')
  }
]

const router = new VueRouter({
  // mode: 'history',
  // base: process.env.BASE_URL,
  routes
})

// 登录鉴权 当前路由是否需要登录
router.beforeEach((to, from, next) => {
  if (!to.meta.needLogin) {
    next()
  } else {
    // 需要登录
    if (isLogin()) {
      next({
        query: {
          from
        }
      })
    } else {
      console.log('触发')
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  }
})

export default router
